package com.forward.controller;

import com.alibaba.fastjson.JSON;
import com.forward.constant.CommonConstant;
import com.forward.constant.SymbolConstant;
import com.forward.entity.*;
import com.forward.utils.*;
import com.forward.vo.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.IOException;

/**
 * @Author: shafei
 * @Date: 2025/02/05 19:19
 * @description：
 **/
@Slf4j
@RestController
@RequestMapping("/doll/forward")
public class ForwardController {

    @Value("${doll.forward.server.url}")
    private String url;
    @Value(value="${jeecg.uploadType}")
    private String uploadType;

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RedisMessagePublisher redisMessagePublisher;

    /**
     * 测试一下redis
     */
    @PostMapping(value = "/test")
    public String test() {
        redisMessagePublisher.publish("mychannel", "test");

        return redisUtil.get("test");
    }

    /**
     * 物品列表清单
     */
    @PostMapping("/doll/products/wxlist")
    public String wxProductsList(@RequestBody DollProducts dollProducts) {
        String sendCodeResponse = null;
        try {
            log.info("GET Request: " + url+"/doll/products/wxlist");
            //将sendCodeBody对象转json字符串
            String sendCodeBodyJson = JSON.toJSONString(dollProducts);
            sendCodeResponse = HttpUtil.sendPostRequest(url+"/doll/products/wxlist", sendCodeBodyJson, dollProducts.getToken());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("GET Response: " + sendCodeResponse);
        return sendCodeResponse;
    }

    /**
     * 物品列表批次清单
     */
    @PostMapping("/doll/products/batchlist")
    public String batchlist(@RequestBody DollProducts dollProducts) {
        String sendCodeResponse = null;
        try {
            log.info("GET Request: " + url+"/doll/products/batchlist");
            //将sendCodeBody对象转json字符串
            String sendCodeBodyJson = JSON.toJSONString(dollProducts);
            sendCodeResponse = HttpUtil.sendPostRequest(url+"/doll/products/batchlist", sendCodeBodyJson, dollProducts.getToken());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("GET Response: " + sendCodeResponse);
        return sendCodeResponse;
    }


    /**
     * 物品清单详情
     * @param dollProducts
     * @return
     */
    @PostMapping("/doll/products/productDetail")
    public String productDetail(@RequestBody DollProducts dollProducts) {
        String sendCodeResponse = null;
        try {
            log.info("POST Request: " + url+"/doll/products/queryById");
            //将sendCodeBody对象转json字符串
            String sendCodeBodyJson = JSON.toJSONString(dollProducts);
            sendCodeResponse = HttpUtil.sendPostRequest(url+"/doll/products/wxqueryById", sendCodeBodyJson, dollProducts.getToken());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("GET Response: " + sendCodeResponse);
        return sendCodeResponse;
    }

    /**
     * 物品列表添加
     */
    @PostMapping("/doll/products/wxadd")
    public String wxProductsAdd(@RequestBody DollProducts dollProducts) {
        log.info("dollProducts: " ,dollProducts.toString());
        String sendCodeResponse = null;
        try {
            //将sendCodeBody对象转json字符串
            String sendCodeBodyJson = JSON.toJSONString(dollProducts);
            sendCodeResponse = HttpUtil.sendPostRequest(url+"/doll/products/add", sendCodeBodyJson, dollProducts.getToken());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("GET Response: " + sendCodeResponse);
        return sendCodeResponse;
    }

    /**
     * 订单列表清单
     */
    @PostMapping("/doll/orders/wxlist")
    public String wxOrderslist(@RequestBody DollOrders d) {
        String sendCodeResponse = null;
        try {
            //将sendCodeBody对象转json字符串
            String bodyJson = JSON.toJSONString(d);
            sendCodeResponse = HttpUtil.sendPostRequest(url+"/doll/orders/wxlist", bodyJson, d.getToken());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("GET Response: " + sendCodeResponse);
        return sendCodeResponse;
    }

    /**
     * 我的消息列表
     */
    @PostMapping("/sys/annountCement/mylist")
    public String mylist(@RequestBody SysAnnouncement d) {
        String sendCodeResponse = null;
        try {
            //将sendCodeBody对象转json字符串
            String bodyJson = JSON.toJSONString(d);
            sendCodeResponse = HttpUtil.sendPostRequest(url+"/sys/annountCement/mylist", bodyJson, d.getToken());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("GET Response: " + sendCodeResponse);
        return sendCodeResponse;
    }

    /**
     * 我的消息详情
     */
    @PostMapping("/sys/annountCement/mylistDetail")
    public String mylistDetail(@RequestBody SysAnnouncement d) {
        String sendCodeResponse = null;
        try {
            //将sendCodeBody对象转json字符串
            String bodyJson = JSON.toJSONString(d);
            sendCodeResponse = HttpUtil.sendPostRequest(url+"/sys/annountCement/mylistDetail", bodyJson, d.getToken());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("GET Response: " + sendCodeResponse);
        return sendCodeResponse;
    }


    /**
     * 申请结算
     */
    @PostMapping("/doll/settlements/applySattlement")
    public String applySattlement(@RequestBody DollSettlements d) {
        String sendCodeResponse = null;
        try {
            //将sendCodeBody对象转json字符串
            String bodyJson = JSON.toJSONString(d);
            sendCodeResponse = HttpUtil.sendPostRequest(url+"/doll/settlements/applySattlement", bodyJson, d.getToken());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("GET Response: " + sendCodeResponse);
        return sendCodeResponse;
    }

    /**
     * 查询我的结算单
     */
    @PostMapping("/doll/settlements/myApplySattlement")
    public String myApplySattlement(@RequestBody DollSettlements d) {
        String sendCodeResponse = null;
        try {
            //将sendCodeBody对象转json字符串
            String bodyJson = JSON.toJSONString(d);
            sendCodeResponse = HttpUtil.sendPostRequest(url+"/doll/settlements/myApplySattlement", bodyJson, d.getToken());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("GET Response: " + sendCodeResponse);
        return sendCodeResponse;
    }

    /**
     * 查询我的结算单详情
     */
    @PostMapping("/doll/settlements/myApplySattlementDetail")
    public String myApplySattlementDetail(@RequestBody DollSettlements d) {
        String sendCodeResponse = null;
        try {
            //将sendCodeBody对象转json字符串
            String bodyJson = JSON.toJSONString(d);
            sendCodeResponse = HttpUtil.sendPostRequest(url+"/doll/settlements/wxqueryById", bodyJson, d.getToken());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("GET Response: " + sendCodeResponse);
        return sendCodeResponse;
    }

    /**
     * 查询我的结算单详情
     */
    @PostMapping("/doll/contanctInfo/wxadd")
    public String contanctInfoAdd(@RequestBody DollContactInfo d) {
        String sendCodeResponse = null;
        try {
            //将sendCodeBody对象转json字符串
            String bodyJson = JSON.toJSONString(d);
            sendCodeResponse = HttpUtil.sendPostRequest(url+"/doll/contanctInfo/add", bodyJson, d.getToken());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("GET Response: " + sendCodeResponse);
        return sendCodeResponse;
    }


    /**
     * 修改用户信息
     */
    @PostMapping("/sys/user/wxUserEdit")
    public String wxUserEdit(@RequestBody SysUser d) {
        String sendCodeResponse = null;
        try {
            //将sendCodeBody对象转json字符串
            String bodyJson = JSON.toJSONString(d);
            sendCodeResponse = HttpUtil.sendPostRequest(url+"/sys/user/wxUserEdit", bodyJson, d.getToken());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("GET Response: " + sendCodeResponse);
        return sendCodeResponse;
    }

    /**
     * 修改用户密码
     */
    @PostMapping("/sys/user/wxUpdatePassword")
    public String wxUpdatePassword(@RequestBody SysUser d) {
        String sendCodeResponse = null;
        try {
            //将sendCodeBody对象转json字符串
            String bodyJson = JSON.toJSONString(d);
            sendCodeResponse = HttpUtil.sendPostRequest(url+"/sys/user/wxUpdatePassword", bodyJson, d.getToken());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("GET Response: " + sendCodeResponse);
        return sendCodeResponse;
    }

    /**
     * 文件上传统一方法
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/image/upload")
    public Result<?> upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result<?> result = new Result<>();
        String savePath = "";
        String bizPath = request.getParameter("biz");

        //LOWCOD-2580 sys/common/upload接口存在任意文件上传漏洞
        if (oConvertUtils.isNotEmpty(bizPath)) {
            if(bizPath.contains(SymbolConstant.SPOT_SINGLE_SLASH) || bizPath.contains(SymbolConstant.SPOT_DOUBLE_BACKSLASH)){
                throw new RuntimeException("上传目录bizPath，格式非法！");
            }
        }

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获取上传文件对象
        MultipartFile file = multipartRequest.getFile("file");
        if(oConvertUtils.isEmpty(bizPath)){
            if(CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)){
                //未指定目录，则用阿里云默认目录 upload
                bizPath = "upload";
                //result.setMessage("使用阿里云文件上传时，必须添加目录！");
                //result.setSuccess(false);
                //return result;
            }else{
                bizPath = "";
            }
        }
        if(CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)){
            //update-begin-author:liusq date:20221102 for: 过滤上传文件类型
            SsrfFileTypeFilter.checkUploadFileType(file);
            //update-end-author:liusq date:20221102 for: 过滤上传文件类型
            //update-begin-author:lvdandan date:20200928 for:修改JEditor编辑器本地上传
            savePath = this.uploadLocal(file,bizPath);
            //update-begin-author:lvdandan date:20200928 for:修改JEditor编辑器本地上传
            /**  富文本编辑器及markdown本地上传时，采用返回链接方式
             //针对jeditor编辑器如何使 lcaol模式，采用 base64格式存储
             String jeditor = request.getParameter("jeditor");
             if(oConvertUtils.isNotEmpty(jeditor)){
             result.setMessage(CommonConstant.UPLOAD_TYPE_LOCAL);
             result.setSuccess(true);
             return result;
             }else{
             savePath = this.uploadLocal(file,bizPath);
             }
             */
        }else{
//            //update-begin-author:taoyan date:20200814 for:文件上传改造
//            savePath = CommonUtils.upload(file, bizPath, uploadType);
//            //update-end-author:taoyan date:20200814 for:文件上传改造
        }
        if(oConvertUtils.isNotEmpty(savePath)){
            result.setMessage(savePath);
            result.setSuccess(true);
        }else {
            result.setMessage("上传失败！");
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 本地文件上传
     * @param mf 文件
     * @param bizPath  自定义路径
     * @return
     */
    private String uploadLocal(MultipartFile mf,String bizPath){
        try {
            String ctxPath = uploadpath;
            String fileName = null;
            File file = new File(ctxPath + File.separator + bizPath + File.separator );
            if (!file.exists()) {
                // 创建文件根目录
                file.mkdirs();
            }
            // 获取文件名
            String orgName = mf.getOriginalFilename();
            orgName = CommonUtils.getFileName(orgName);
            if(orgName.indexOf(SymbolConstant.SPOT)!=-1){
                fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."));
            }else{
                fileName = orgName+ "_" + System.currentTimeMillis();
            }
            String savePath = file.getPath() + File.separator + fileName;
            File savefile = new File(savePath);
            FileCopyUtils.copy(mf.getBytes(), savefile);
            String dbpath = null;
            if(oConvertUtils.isNotEmpty(bizPath)){
                dbpath = bizPath + File.separator + fileName;
            }else{
                dbpath = fileName;
            }
            if (dbpath.contains(SymbolConstant.DOUBLE_BACKSLASH)) {
                dbpath = dbpath.replace(SymbolConstant.DOUBLE_BACKSLASH, SymbolConstant.SINGLE_SLASH);
            }
            return dbpath;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return "";
    }


}
